import axios, { request } from "axios";
import {Message} from "element-ui";
import store from "@/store";
import alter from '../utils/alter'
import router from "@/router";

let baseUrl = "http://localhost:8888"

const service = axios.create({
    baseURL: baseUrl, // url = base api url + request url
    withCredentials: false, // send cookies when cross-domain requests
    timeout: 1000*12 // 请求超时
})




// 添加请求拦截器，对 token 做统一处理
service.interceptors.request.use(config => {

    const token = localStorage.getItem("token")
    console.log("token:"+localStorage.getItem("token"))
    if(token) {
        config.headers.token = token
    }

    return config;
}, error => {
    return Promise.reject(error)
});

const alertBox = new alter()
service.interceptors.response.use( resp => {
    let code = resp.data.code
    let msg = resp.data.msg
    if (code === 200) {
        return resp.data
    } else if(code === 401) {
        alertBox.error("当前账户已失效，请重新登录")
        store.commit("SET_TOKEN", '');
        store.commit("SET_USERINFO",JSON.stringify(''))
        localStorage.clear();
        router.push("/login")
    } else if(code === 403) {
        alertBox.error(msg)
    } else if(code === 400501) {
        alertBox.error(msg)
    }
    return resp
},error => {
    return Promise.reject(error)
})

export function download(url, data) {
    return service.post(url, data, {responseType: 'arraybuffer'}).then((res) => {
        const content = res.data
        // let filename = res.headers["content-disposition"].split(';')[1];
        const headerFilename = res.headers['content-disposition']?.split(';')[1].split('=')[1];
        const filename = decodeURIComponent(headerFilename);
        const blob = new Blob([content], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"})
        if ('download' in document.createElement('a')) {
            const elink = document.createElement('a')
            elink.download = filename
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href)
            document.body.removeChild(elink)
            Message.success("导出成功")
        } else {
            navigator.msSaveBlob(blob, filename)
        }

    }).catch((r) => {
        Message.error("发生错误:" + r)
        console.error(r)
    })

    // return request.post(url, data, { responseType: 'arraybuffer' })
}

export default service;
